<!--
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 * No deletion without permission, or be held responsible to law.
 * @author ThinkGem
-->
<template>
  <BasicModal
    v-bind="$attrs"
    :title="t('任务退回')"
    @register="registerModal"
    @ok="handleSubmit"
    :minHeight="120"
    :width="700"
  >
    <BasicForm @register="registerForm">
      <template #backActivityTable>
        <div class="mt-1 mb-3">
          <RadioGroup
            :options="[
              { label: t('退回到发起人'), value: '1' },
              { label: t('退回到上一步'), value: '2' },
              { label: t('退回任意环节'), value: '3' },
            ]"
            :value="backRadioGroup"
            @click="handleBackRadioGroupClick"
          />
        </div>
        <BasicTable @register="registerBackActivityTable" @row-click="handleBackActivityRowClick" />
      </template>
    </BasicForm>
  </BasicModal>
</template>
<script lang="ts">
  export default defineComponent({
    name: 'JeeSiteBpmTaskBack',
    inheritAttrs: false,
  });
</script>
<script lang="ts" setup>
  import { defineComponent, ref } from 'vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, FormSchema, useForm, RadioGroup } from '/@/components/Form';
  import { BasicTable, useTable } from '/@/components/Table';
  import { bpmBack, bpmBackTask } from '/@/api/bpm';

  const emit = defineEmits(['success', 'register']);

  const { t } = useI18n('bpm.button');
  const { showMessage, showMessageModal } = useMessage();
  const record = ref<Recordable>({});

  const backRadioGroup = ref<String>('1');
  const backActivity = ref<Recordable[]>([]);

  const inputFormSchemas: FormSchema[] = [
    {
      label: t('当前环节'),
      field: 'name',
      component: 'Input',
      render: ({ values }) => {
        return values.name || t('未设置环节名');
      },
      required: true,
    },
    {
      label: t('退回到哪'),
      field: 'activityId',
      component: 'Select',
      colProps: { lg: 23, md: 24 },
      slot: 'backActivityTable',
      required: true,
    },
    {
      label: t('退回原因'),
      field: 'comment',
      component: 'InputTextArea',
      componentProps: {
        placeholder: '请输入退回原因',
        maxlength: 500,
        rows: 3,
      },
    },
  ];

  const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
    labelWidth: 120,
    schemas: inputFormSchemas,
    baseColProps: { lg: 23, md: 24 },
  });

  const [registerBackActivityTable, backActivityTable] = useTable({
    columns: [
      {
        title: t('环节名称'),
        dataIndex: 'activityName',
        width: 100,
      },
      {
        title: t('处理人名称'),
        dataIndex: 'assigneeName',
        width: 80,
      },
      {
        title: t('处理时间'),
        dataIndex: 'startTime',
        width: 80,
      },
    ],
    rowKey: 'activityId',
    rowSelection: { type: 'radio', columnWidth: 0 },
    pagination: false,
    bordered: true,
    size: 'small',
    inset: true,
  });

  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    setModalProps({ loading: true });
    await resetFields();
    record.value = data.task || {};
    // console.log(record.value);
    setFieldsValue(record.value);
    const res = await bpmBack({ id: data.task.id });
    backActivity.value = res.backActivity || [];
    backActivityTable.setTableData(backActivity.value);
    handleBackRadioGroupClick();
    setModalProps({ loading: false });
  });

  function handleBackRadioGroupClick(e: any = undefined) {
    const key = e?.target?.value || backRadioGroup.value;
    if (key && backActivity.value.length > 0) {
      if (key == '1') {
        const row = backActivity.value[0];
        backActivityTable.setSelectedRowKeys([row.activityId]);
      } else if (key == '2') {
        const row = backActivity.value[backActivity.value.length - 1];
        backActivityTable.setSelectedRowKeys([row.activityId]);
      } else {
        showMessage(t('请选择一个退回环节'));
        backActivityTable.setSelectedRowKeys([]);
      }
    }
  }

  function handleBackActivityRowClick(row: Recordable) {
    const key = row.activityId;
    if (key && backActivity.value.length > 0) {
      const keyIndex = backActivity.value.findIndex((item) => item.activityId === key);
      backRadioGroup.value =
        keyIndex == 0 ? '1' : keyIndex == backActivity.value.length - 1 ? '2' : '3';
    }
  }

  async function handleSubmit() {
    try {
      if (record.value.id == '') {
        showMessage(t('任务ID不能为空'));
        return;
      }
      if (backActivityTable.getSelectRowKeys().length == 0) {
        showMessage(t('请选择退回到哪') + backActivityTable.getSelectRowKeys());
        return;
      }
      const data = await validate();
      setModalProps({ confirmLoading: true });
      data.id = record.value.id;
      data.activityId = backActivityTable.getSelectRowKeys()[0];
      const keyIndex = backActivity.value.findIndex((item) => item.activityId === data.activityId);
      data.nextUserCodes = backActivity.value[keyIndex].assignee;
      // console.log('submit', data);
      const res = await bpmBackTask(data);
      showMessageModal({ content: res.message });
      setTimeout(closeModal);
      emit('success');
    } catch (error: any) {
      if (error && error.errorFields) {
        showMessage(t('您填写的信息有误，请根据提示修正。'));
      }
      console.log('error', error);
    } finally {
      setModalProps({ confirmLoading: false });
    }
  }
</script>
